<template>
  <div class="page-container">
    <a-form-model ref="form" :model="form" :rules="rules" :label-col="{ span: 4 }" :wrapper-col="{ span: 8 }">
      <a-form-model-item label="选择接收人">
        <template v-if="form.userIds.length">
          <span
            >已选<a>{{ form.userIds.length }}</a
            >人</span
          >
          <a-button class="_ml-10" @click="handleViewUser">查看</a-button>
          <a-button v-if="dataSource != 'applyUserList'" class="_ml-10" @click="handleAddUser">添加</a-button>
        </template>
        <a-button v-else @click="handleAddUser">点击添加接收人</a-button>
      </a-form-model-item>
      <a-form-model-item label="消息类型" prop="smsTemplateTypeId">
        <SendMessageSelect
          :dataSource="dataSource"
          :modelValue.sync="form.smsTemplateTypeId"
          placeholder="请选择消息类型"
          noSkip
          @change="handleTypeChange"
        />
      </a-form-model-item>
      <a-form-model-item v-if="showObject" label="关联内容" prop="objectId">
        <a-select
          style="width: 300px"
          v-model="form.objectId"
          show-search
          :filter-option="filterOption"
          :disabled="dataSource === DataSourceEnum.REGISTERLIST"
          placeholder="下拉选择或搜索模板关联内容"
          @change="handleObjectChange"
        >
          <a-select-option v-for="item in objectList" :value="item.id" :key="item.id">{{ item.title }}</a-select-option>
        </a-select>
      </a-form-model-item>
      <a-form-model-item label="消息标题" prop="title">
        <a-input v-model="form.title" placeholder="请输入消息标题" />
      </a-form-model-item>
      <a-form-model-item label="选择发送方式" prop="sendTypes">
        <a-checkbox-group v-model="form.sendTypes">
          <div class="disFlxAC _mb-20">
            <div>
              <a-checkbox value="wechat" :disabled="!wxTemplateList.length"
                >微信 （仅可发送给本组织已关注公众号的用户）</a-checkbox
              >
              <div class="sendType-box _mt-10 _mb-50" v-show="form.sendTypes.includes('wechat')">
                <a-form-model-item label="选择模板">
                  <a-select
                    v-model="form.wechatTemplateId"
                    style="width: 200px"
                    placeholder="请选择已有微信模板"
                    @change="handleWxTempChange"
                  >
                    <a-select-option v-for="item in wxTemplateList" :value="item.sceneCode" :key="item.sceneCode">{{
                      item.sceneName
                    }}</a-select-option>
                  </a-select>
                </a-form-model-item>
                <a-form-model-item label="测试微信">
                  <div class="disFlxAC">
                    <a-input
                      v-model="form.wxPhoneList"
                      placeholder="请输入手机号，多个手机号用英文逗号隔开"
                      style="width: 400px"
                    />
                    <a-button class="_ml-10" type="primary" @click="handleSend('wxPhoneList', ['wechat'])"
                      >发送测试通知</a-button
                    >
                  </div>
                </a-form-model-item>
              </div>
            </div>
            <div class="temp-warp _ml-20" v-show="form.sendTypes.includes('wechat') && form.wechatTemplateId">
              <img class="bg-img" src="@/assets/icons/message/wxBg.png" alt="" />
              <div class="temp-content">
                <div class="title">
                  <span>{{ wxTemplateObj.sceneName }}</span>
                </div>
                <div class="text">{{ wxTemplateObj.displayContent }}</div>
                <div class="disFlxJS bottom-info">
                  <div class="left disFlxAC">
                    <img class="user-icon" src="@/assets/icons/default_userIcon.png" alt="" />
                    <span class="_ml-2">小程序名称</span>
                  </div>
                  <div class="right disFlxAC">
                    <img class="wx-icon" src="@/assets/icons/wx-icon.png" alt="" />
                    <span class="_ml-2 _mr-5">小程序</span>
                    <img class="right-icon" src="@/assets/icons/right.png" alt="" />
                  </div>
                </div>
              </div>
            </div>
          </div>
          <div v-if="!showRichText" class="disFlxAC">
            <div>
              <a-checkbox value="sms" :disabled="!templateList.length"
                >短信（剩余{{ balance }}条，若需充值联系服务商）</a-checkbox
              >
              <div class="sendType-box _mt-10 _mb-50" v-show="form.sendTypes.includes('sms')">
                <a-form-model-item label="选择短信模板">
                  <a-select
                    v-model="form.smsTemplateId"
                    style="width: 200px"
                    placeholder="请选择已有短信模板"
                    @change="handleSmsTempChange"
                  >
                    <a-select-option v-for="item in templateList" :value="item.id" :key="item.id">{{
                      item.name
                    }}</a-select-option>
                  </a-select>
                </a-form-model-item>
                <a-form-model-item label="测试短信">
                  <div class="disFlxAC">
                    <a-input
                      v-model="form.smsPhoneList"
                      placeholder="请输入手机号，多个手机号用英文逗号隔开"
                      style="width: 400px"
                    />
                    <a-button class="_ml-10" type="primary" @click="handleSend('smsPhoneList', ['sms'])"
                      >发送测试短信</a-button
                    >
                  </div>
                </a-form-model-item>
              </div>
            </div>
            <div class="temp-warp _ml-20" v-show="form.sendTypes.includes('sms') && form.smsTemplateId">
              <img class="bg-img" src="@/assets/icons/message/smsBg.png" alt="" />
              <div class="temp-content _p-12">
                <span class="fw-6">【{{ smsSignText }}】</span>
                <span class="text">{{ smsTemplateObj.smsZhContent }}</span>
              </div>
            </div>
          </div>
        </a-checkbox-group>
        <div v-show="showRichText" class="py-4" style="width: 800px">
          <div class="summernote"></div>
        </div>
      </a-form-model-item>
      <div class="fixed-btn">
        <a-button @click="handleBack">取消</a-button>
        <a-button type="primary" class="_ml-10" @click="handleSend('')" :loading="loading">立即发送</a-button>
      </div>
    </a-form-model>
    <SelectMember ref="SelectMember" :dataSource="dataSource" :objectId="form.objectId" @confirmUser="getConfirmUser" />
    <SelectedUserList
      ref="SelectedUserList"
      :list="form.userIds"
      :dataSource="dataSource"
      :objectId="form.objectId"
      @del="getConfirmUser"
    />
  </div>
</template>

<script>
import SelectMember from '@/components/ChooseUser/selectMember'
import SelectedUserList from '@/components/ChooseUser/selectedUserList'
import {
  SmsObjectList,
  SmsTemplateList,
  MessageSend,
  MessageRecordFindBalance,
  WechatTemplateListByTypeId,
  SmsSign
} from '@/api/operations/message'
import { customUpload, uploadApi } from '@/api/upload'
import { debounce } from '@/utils/common'
import SendMessageSelect from '@/views/operations/message/components/sendMessageSelect'
import { DataSourceEnum } from '@/enums/member'
import { isArray } from 'lodash-es'

export default {
  components: { SelectMember, SelectedUserList, SendMessageSelect },
  data() {
    return {
      DataSourceEnum,
      visible: false,
      form: {
        title: undefined,
        smsTemplateTypeId: undefined,
        userIds: [],
        smsTemplateId: undefined,
        wechatTemplateId: undefined,
        objectId: undefined,
        sendTypes: [],
        smsPhoneList: undefined,
        wxPhoneList: undefined
      },
      rules: {
        smsTemplateTypeId: [{ required: true, message: '请选择消息类型', trigger: 'change' }],
        objectId: [{ required: true, message: '请选择关联内容', trigger: 'change' }],
        title: [{ required: true, message: '请输入消息标题', trigger: 'change' }],
        sendTypes: [{ required: true, message: '请选择发送方式', trigger: 'change' }]
      },
      isWx: true,
      isSms: false,
      objectList: [], //消息关联对象下拉数据
      templateList: [],
      wxTemplateList: [],
      smsTemplateObj: {}, //选中的短信模板对象数据
      wxTemplateObj: {}, //选中的微信模板对象数据
      dataSource: 'userList',
      selectedUsers: [],
      showObject: true,
      showRichText: false,
      balance: 0,
      smsSignText: '',
      loading: false
    }
  },
  methods: {
    debounce,
    async getMessageRecordFindBalance() {
      let res = await MessageRecordFindBalance()
      this.balance = res.data || 0
    },
    //消息类型change事件
    async handleTypeChange(id, data, isDefault) {
      this.form.smsTemplateTypeId = id
      let item = data[data.length - 1]
      this.dataSource = item.dataSource
      this.showObject = item.associatedObjects ? true : false
      this.form.smsTemplateId = undefined
      this.form.wechatTemplateId = undefined
      this.getWechatTemplateListByTypeId(item.id)
      this.getSmsTemplateList(item.id)
      //自定义类型
      if (item.customType === 1) {
        this.showRichText = true
        this.form.sendTypes = ['wechat']
      } else {
        this.showRichText = false
      }

      //不显示关联内容&非自定义类型，消息标题显示已选中消息类型名称
      if (!this.showObject && item.customType !== 1) {
        this.form.title = item.name
        return
      }

      //获取关联内容数据
      let res = await SmsObjectList(item.associatedObjects)
      this.objectList = res.data || []

      let object = this.objectList[0]
      if (isDefault) object = this.objectList.find(f => f.id == this.form.objectId) || object

      if (this.dataSource !== this.DataSourceEnum.REGISTERLIST) {
        this.form.objectId = object && object.id
      }
      //消息标题已设置&首次加载时，不覆盖已有标题
      if (this.form.title && isDefault) return
      this.form.title = object && object.title
    },
    //关联内容change对象
    handleObjectChange(val) {
      let item = this.objectList.find(f => f.id === val)
      this.form.title = item.title
    },
    filterOption(input, option) {
      return option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
    },
    afterClose() {
      this.$refs.form.resetFields()
    },
    //添加接收人
    handleAddUser() {
      this.$refs.SelectMember.moduleShow(this.form.userIds)
    },
    getConfirmUser(ids) {
      if (isArray(ids)) {
        this.form.userIds = ids
      } else {
        // 暂时兼容之前老数据，从其他页面勾选跳转消息时
        let list = Object.keys(ids).reduce((pre, cur) => {
          pre = pre.concat(ids[cur])
          return pre
        }, [])

        this.form.userIds = list.map(item => item.userId)
      }
    },
    //查看已选中人员
    handleViewUser() {
      this.$refs.SelectedUserList.moduleShow()
    },

    //获取微信模板下拉
    async getWechatTemplateListByTypeId(id) {
      let res = await WechatTemplateListByTypeId({
        typeId: id,
        size: 100
      })
      this.wxTemplateList = res.data || []
      let index = this.form.sendTypes.findIndex(val => val === 'wechat')
      if (!this.wxTemplateList.length) {
        if (index != -1) this.form.sendTypes.splice(index, 1)
      } else {
        this.form.wechatTemplateId = this.wxTemplateList[0].sceneCode
        if (index === -1) this.form.sendTypes.push('wechat')
        this.handleWxTempChange(this.form.wechatTemplateId)
      }
    },
    //获取短信模板下拉
    async getSmsTemplateList(id) {
      let res = await SmsTemplateList({
        smsTemplateTypeId: id,
        size: 100
      })
      this.templateList = res.data || []
      let index = this.form.sendTypes.findIndex(val => val === 'sms')
      if (!this.templateList.length) {
        if (index != -1) this.form.sendTypes.splice(index, 1)
      } else {
        this.form.smsTemplateId = this.templateList[0].id
        if (index === -1) this.form.sendTypes.push('sms')
        this.handleSmsTempChange(this.form.smsTemplateId)
      }
    },
    handleSend(field, sendTypes) {
      this.$refs.form.validate(async valid => {
        if (valid) {
          let { smsTemplateTypeId } = this.form
          let phoneList = this.form[field]
          if (field && !phoneList) return this.$message.error('请输入手机号码')
          // 获取value
          let text = $('.summernote').summernote('code') || undefined
          try {
            if (!field) this.loading = true
            await MessageSend({
              ...this.form,
              smsTemplateTypeId: smsTemplateTypeId.slice(-1)[0],
              userIds: field ? [] : this.form.userIds,
              phoneList: phoneList && phoneList.split(','),
              customPage: text,
              sendTypes: sendTypes || this.form.sendTypes
            })
            if (!field) this.loading = false
            this.$message.success('发送成功')
            if (!field) this.handleBack()
          } catch (error) {
            this.loading = false
          }
        }
      })
    },
    handleWxTempChange(val) {
      let item = this.wxTemplateList.find(f => f.sceneCode === val)
      this.wxTemplateObj = item
    },
    handleSmsTempChange(val) {
      let item = this.templateList.find(f => f.id === val)
      this.smsTemplateObj = item
    },
    handleBack() {
      this.$router.back()
    },
    //获取短信签名
    async getSmsSign() {
      let res = await SmsSign()
      this.smsSignText = res.data || ''
    }
  },
  created() {
    let { dataSource, objectId, title, messageChannelList } = this.$route.query
    this.dataSource = dataSource || 'userList'
    this.form.title = this.form.title || title
    this.form.objectId = (objectId && Number(objectId)) || undefined
    this.getConfirmUser(this.$store.state.message.pageSelectedObj)
    const smsTemplateObj = this.$store.state.message.smsTemplateObj

    this.form.smsTemplateTypeId = smsTemplateObj.ids.length ? smsTemplateObj.ids : undefined
    smsTemplateObj.data.length && this.handleTypeChange(smsTemplateObj.ids, smsTemplateObj.data, true)

    if (messageChannelList) {
      let list = JSON.parse(messageChannelList) || []
      this.form.sendTypes = []
      list.map(item => {
        this.form.sendTypes.push(item.messageChannel)
        if (item.messageChannel === 'sms') {
          this.form.smsTemplateId = item.templateId
        } else if (item.messageChannel === 'wechat') {
          this.form.wechatTemplateId = item.templateId
        }
      })
    }
    this.getMessageRecordFindBalance()
    this.getSmsSign()
  },
  mounted() {
    $(document).ready(function() {
      $('.summernote').summernote({
        height: 500,
        tabsize: 2,
        focus: true,
        shortcuts: true,
        placeholder: '这是一个富文本编辑器',
        callbacks: {
          onImageUpload: function(file) {
            // TODO 图片上传逻辑
            Object.keys(file).forEach(k => {
              const formData = new FormData()
              formData.append('file', file[k])
              customUpload(uploadApi.customImg, formData).then(res => {
                if (res.code === 0) {
                  $('.summernote').summernote('insertImage', res.data.imagePathSmall)
                }
              })
            })
          }
        }
      })
      // 设置value
      $('.summernote').summernote('code', '')
    })
  }
}
</script>

<style lang="less" scoped>
.sendType-box {
  background-color: #eee;
  width: 100%;
  padding: 20px;
}
.fixed-btn {
  position: fixed;
  bottom: 0;
  left: 0;
  z-index: 9;
  width: 100%;
  padding: 16px 0;
  display: flex;
  align-items: center;
  justify-content: center;
  background: #fff;
  box-shadow: 0 0 5px 5px rgba(0, 0, 0, 0.1);
}
.temp-warp {
  width: 280px;
  height: 280px;
  position: relative;
  font-size: 12px;
  .bg-img {
    position: absolute;
    top: 0;
    left: 0;
    z-index: 1;
    width: 280px;
    height: 280px;
  }
  .temp-content {
    position: absolute;
    left: 20px;
    top: 95px;
    z-index: 2;
    width: 240px;
    background-color: #fff;
    border-radius: 5px;
    box-shadow: 0 0 2px 2px rgba(0, 0, 0, 0.05);
    min-height: 150;
    .title {
      padding: 12px;
      font-weight: bold;
    }
    .text {
      white-space: break-spaces;
      // margin: 10px 0;
      margin-bottom: 15px;
      padding: 0 12px;
    }
    .bottom-info {
      padding: 5px 12px;
      border-top: 1px #eee solid;
      .left {
        .user-icon {
          width: 20px;
          height: 20px;
        }
      }
      .right {
        .wx-icon {
          width: 10px;
          height: 10px;
        }
        .right-icon {
          width: 10px;
          height: 10px;
        }
      }
    }
  }
}
</style>
